<template>
  <view class="publish-page">
    <!-- 顶部导航 -->
    <view class="nav">
      <view class="back" @click="goBack">‹</view>
      <text class="title">发布病友圈</text>
      <view class="right"></view>
    </view>

    <scroll-view scroll-y class="body" :style="{ paddingTop: '88rpx' }">
      <!-- 基础信息 -->
      <view class="card">
        <view class="field">
          <text class="label">* 标题（最多20个字）</text>
          <input class="input" v-model.trim="form.title" maxlength="20" placeholder="请输入标题" />
        </view>
        <view class="field">
          <text class="label">* 就诊科室</text>
          <view class="picker" @click="toggleDeptPanel">
            <text>{{ deptName || '请选择就诊科室' }}</text>
            <text style="margin-left:auto;color:#999;">{{ showDeptPanel ? '▲' : '▼' }}</text>
          </view>
        </view>
        <!-- 科室 chips 面板 -->
        <view v-if="showDeptPanel" class="chips-wrap">
          <view class="chip" v-for="d in departments" :key="d.id" :class="{active: form.departmentId===d.id}" @click="selectDept(d)">{{ d.name }}</view>
        </view>
        <view class="field">
          <text class="label">* 主要病症</text>
          <view class="picker" @click="toggleDiseasePanel">
            <text>{{ form.diseaseName || '请选择主要病症' }}</text>
            <text style="margin-left:auto;color:#999;">{{ showDiseasePanel ? '▲' : '▼' }}</text>
          </view>
        </view>
        <!-- 病症 chips 面板 -->
        <view v-if="showDiseasePanel" class="chips-wrap">
          <view class="chip" :class="{active: manualDiseaseInput}" @click="enableManualDisease">手动输入</view>
          <view class="chip" v-for="d in diseaseOptions" :key="d.id" :class="{active: form.diseaseId===d.id}" @click="selectDisease(d)">{{ d.name }}</view>
        </view>
        <!-- 手动输入病症（兜底） -->
        <view class="field" v-if="manualDiseaseInput || (!diseaseOptions.length && form.departmentId)">
          <input class="input" v-model.trim="form.diseaseName" placeholder="请输入主要病症" />
        </view>
        <view class="field">
          <text class="label">* 病症详情（不超过300字）</text>
          <textarea class="textarea" v-model.trim="form.diseaseDetail" :maxlength="300" placeholder="请详细描述症状" />
          <text class="count">{{ (form.diseaseDetail||'').length }}/300</text>
        </view>
      </view>

      <!-- 就诊经历 -->
      <view class="card">
        <view class="field">
          <text class="label">最近一段治疗经历</text>
          <input class="input" v-model.trim="form.hospitalName" placeholder="请输入医院名称（可选）" />
        </view>
        <view class="field two">
          <view class="half">
            <text class="label">开始时间</text>
            <picker mode="date" @change="e=>form.startTime=e.detail.value">
              <view class="picker"><text>{{ form.startTime || '请选择' }}</text></view>
            </picker>
          </view>
          <view class="half">
            <text class="label">结束时间</text>
            <picker mode="date" @change="e=>form.endTime=e.detail.value">
              <view class="picker"><text>{{ form.endTime || '请选择' }}</text></view>
            </picker>
          </view>
        </view>
        <view class="field">
          <text class="label">治疗过程</text>
          <textarea class="textarea" v-model.trim="form.treatmentProcess" placeholder="请输入治疗过程（可选）" />
        </view>
      </view>

      <!-- 图片上传 -->
      <view class="card">
        <view class="field">
          <text class="label">图片（最多6张，长按可排序）</text>
          <view class="images">
            <view class="img-item" v-for="(url, i) in images" :key="i">
              <image class="img" :src="url" mode="aspectFill" @click="preview(url)" />
              <view class="del" @click="remove(i)">×</view>
            </view>
            <view v-if="images.length < 6" class="img-item upload" @click="chooseAndUpload">
              <text class="plus">＋</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 开启悬赏 -->
      <view class="card">
        <view class="field row">
          <text class="label">提升悬赏额度</text>
          <switch :checked="form.rewardEnabled === 1" @change="onRewardSwitch" color="#667eea" />
        </view>
        <view v-if="form.rewardEnabled === 1">
          <view class="reward-tip">提升额度可获得更多的关注，得到更多建议</view>
          <view class="amounts">
            <view
              class="amount-chip"
              v-for="n in rewardPresets"
              :key="n"
              :class="{ active: selectedPreset === n }"
              @click="selectPreset(n)"
            >{{ n }}H币</view>
            <view class="amount-chip" :class="{ active: customMode }" @click="enableCustom">自定义</view>
          </view>
          <view class="field" v-if="customMode">
            <input class="input" type="number" v-model.number="form.rewardCoin" placeholder="请输入赏币数量" />
          </view>
          <view v-if="balanceLoading" class="balance">余额加载中...</view>
          <view v-else-if="coinBalance !== null" class="balance">当前H币余额 {{ coinBalance }}。不足？<text class="recharge" @click="goRecharge">去充值</text></view>
        </view>
      </view>

      <view class="safe" />
    </scroll-view>

    <!-- 提交按钮 -->
    <view class="footer">
      <button class="submit" :disabled="submitting" @click="submit">{{ submitting ? '发布中...' : '发布' }}</button>
    </view>
  </view>
</template>

<script>
import { getDeptWithDiseases } from '@/api/department'
import { publishCircle } from '@/api/circle'
import upload from '@/utils/upload'
import { getMyHcoin } from '@/api/patient'
import config from '@/config.js'

export default {
  data() {
    return {
      departments: [],
      deptName: '',
      showDeptPanel: false,
      showDiseasePanel: false,
      deptDiseaseMap: {},
      diseaseOptions: [],
      manualDiseaseInput: false,
      images: [],
      submitting: false,
      // 悬赏区
      rewardPresets: [10, 20, 30],
      selectedPreset: null,
      customMode: false,
      coinBalance: null,
      balanceLoading: false,
      form: {
        title: '',
        departmentId: null,
        diseaseId: null,
        diseaseName: '',
        diseaseDetail: '',
        startTime: '',
        endTime: '',
        treatmentProcess: '',
        rewardEnabled: 0,
        rewardCoin: null,
        hospitalName: '',
        image: ''
      }
    }
  },
  onLoad() {
    this.fetchDeptWithDiseases()
  },
  watch: {
    'form.rewardCoin'(val) {
      // 仅在自定义模式下做约束
      if (!this.customMode) return
      if (val === '' || val == null) return
      let n = Number(val)
      if (!Number.isFinite(n)) return
      n = Math.floor(n)
      if (n <= 0) {
        if (this.form.rewardCoin !== null) this.form.rewardCoin = null
        return
      }
      if (this.coinBalance !== null && n > this.coinBalance) {
        if (this.form.rewardCoin !== this.coinBalance) this.form.rewardCoin = this.coinBalance
        uni.showToast({ title: '超过余额，已调整为余额上限', icon: 'none' })
      } else {
        if (this.form.rewardCoin !== n) this.form.rewardCoin = n
      }
    }
  },
  methods: {
    goBack() { uni.navigateBack() },
    async fetchDeptWithDiseases() {
      try {
        const res = await getDeptWithDiseases()
        // 兼容多种返回结构：根数组 / data|rows|records / list / data.rows / data.records
        const list =
          (Array.isArray(res?.data) && res.data) ||
          (Array.isArray(res?.rows) && res.rows) ||
          (Array.isArray(res?.records) && res.records) ||
          (Array.isArray(res?.list) && res.list) ||
          (Array.isArray(res?.data?.rows) && res.data.rows) ||
          (Array.isArray(res?.data?.records) && res.data.records) ||
          (Array.isArray(res) && res) ||
          []
        const map = {}
        const depFallback = []
        ;(list || []).forEach(item => {
          const deptId = item.deptId ?? item.id ?? item.departmentId
          const deptName = item.deptName ?? item.name ?? item.departmentName
          const diseasesRaw =
            item.diseases ??
            item.diseaseList ??
            item.diseaseVOList ??
            item.diseaseVos ??
            item.children ??
            item.items
          const diseases = Array.isArray(diseasesRaw)
            ? diseasesRaw.map(x => ({
                id: x.diseaseId ?? x.id ?? x.disId ?? x.code,
                name: x.diseaseName ?? x.name ?? x.title
              }))
            : []
          if (deptId) {
            map[deptId] = diseases
            depFallback.push({ id: deptId, name: deptName })
            if (!diseases.length) {
              // 便于排查后端字段差异（仅开发阶段调试用）
              try { console.warn('[dept no diseases]', item) } catch(_) {}
            }
          }
        })
        this.deptDiseaseMap = map
        // 直接用 diseases 接口结果作为科室列表（唯一来源）
        const seen = new Set()
        this.departments = depFallback.filter(d => !seen.has(d.id) && seen.add(d.id))
      } catch (e) {
        // ignore
      }
    },
    toggleDeptPanel() { this.showDeptPanel = !this.showDeptPanel },
    toggleDiseasePanel() { this.showDiseasePanel = !this.showDiseasePanel },
    selectDept(item) {
      this.form.departmentId = item?.id || null
      this.deptName = item?.name || ''
      this.showDeptPanel = false
      // 联动病症
      this.diseaseOptions = this.deptDiseaseMap[this.form.departmentId] || []
      this.form.diseaseId = null
      this.form.diseaseName = ''
      // 自动展开病症面板
      if (this.diseaseOptions.length) {
        this.manualDiseaseInput = false
        this.showDiseasePanel = true
      } else {
        this.manualDiseaseInput = true
        this.showDiseasePanel = true
      }
    },
    selectDisease(item) {
      this.form.diseaseId = item?.id || null
      this.form.diseaseName = item?.name || ''
      this.manualDiseaseInput = false
      this.showDiseasePanel = false
    },
    enableManualDisease() {
      // 切换手动输入模式（可取消）
      if (this.manualDiseaseInput) {
        // 取消手动输入，不清空已有 diseaseName，保留用户输入
        this.manualDiseaseInput = false
      } else {
        // 开启手动输入，清空已选 diseaseId
        this.form.diseaseId = null
        this.manualDiseaseInput = true
      }
    },
    onDeptChange(e) {
      const idx = Number(e.detail.value)
      const item = this.departments[idx]
      this.form.departmentId = item?.id || null
      this.deptName = item?.name || ''
    },
    onRewardSwitch(e) {
      const on = e.detail.value
      this.form.rewardEnabled = on ? 1 : 0
      if (on) {
        // 开启时默认选中第一个档位
        this.selectedPreset = this.rewardPresets[0]
        this.customMode = false
        this.form.rewardCoin = this.selectedPreset
        // 拉取余额
        this.fetchCoinBalance()
      } else {
        // 关闭时清空
        this.selectedPreset = null
        this.customMode = false
        this.form.rewardCoin = null
      }
    },
    selectPreset(n) {
      if (this.coinBalance !== null && n > this.coinBalance) {
        uni.showModal({
          title: '余额不足',
          content: 'H币余额不足，是否前往充值？',
          confirmText: '去充值',
          cancelText: '取消',
          success: (res) => {
            if (res && res.confirm) this.goRecharge()
          }
        })
        return
      }
      this.customMode = false
      this.selectedPreset = n
      this.form.rewardCoin = n
    },
    enableCustom() {
      this.selectedPreset = null
      this.customMode = true
      if (!this.form.rewardCoin) this.form.rewardCoin = null
    },
    async fetchCoinBalance() {
      if (this.balanceLoading) return
      this.balanceLoading = true
      try {
        const res = await getMyHcoin()
        const raw = (res && res.data) != null ? res.data : res
        const n = Number(raw)
        this.coinBalance = Number.isFinite(n) ? n : 0
        // 若默认选择档位超出余额，进行纠正
        if (this.form.rewardEnabled === 1 && this.selectedPreset && this.coinBalance !== null && this.selectedPreset > this.coinBalance) {
          uni.showToast({ title: '余额不足，已切换为自定义', icon: 'none' })
          this.selectedPreset = null
          this.customMode = true
          this.form.rewardCoin = this.coinBalance > 0 ? this.coinBalance : null
        } else if (this.form.rewardEnabled === 1 && this.customMode) {
          const v = Number(this.form.rewardCoin)
          if (Number.isFinite(v) && this.coinBalance !== null && v > this.coinBalance) {
            this.form.rewardCoin = this.coinBalance > 0 ? this.coinBalance : null
            uni.showToast({ title: '超过余额，已调整为余额上限', icon: 'none' })
          }
        }
      } catch (e) {
        this.coinBalance = null
        uni.showToast({ title: '余额获取失败', icon: 'none' })
      } finally {
        this.balanceLoading = false
      }
    },
    goRecharge() {
      // 优先使用配置中的 H5 充值地址（通用WebView）
      if (config && config.rechargeUrl) {
        const target = `/pages/common/webview/index?title=${encodeURIComponent('充值')}&url=${encodeURIComponent(config.rechargeUrl)}`
        return uni.navigateTo({ url: target })
      }
      // 其次尝试原生页面路径（若不存在会 fail）
      uni.navigateTo({ url: '/pages/wallet/recharge', fail: () => uni.showToast({ title: '充值功能开发中', icon: 'none' }) })
    },
    preview(url) { uni.previewImage({ urls: [url] }) },
    remove(i) { this.images.splice(i, 1) },
    isNetUrl(u){ return /^(https?:)?\/\//.test(u) },
    async chooseAndUpload() {
      try {
        const choose = await new Promise((resolve, reject) => {
          uni.chooseImage({ count: Math.min(6 - this.images.length, 6), sizeType: ['compressed'], sourceType: ['album','camera'], success: resolve, fail: reject })
        })
        // 本地预览模式：不请求后端，直接使用临时路径
        const files = choose.tempFilePaths || []
        files.forEach(fp => {
          if (this.images.length < 6) this.images.push(fp)
        })
      } catch(_) { uni.showToast({ title:'选择图片失败', icon:'none' }) }
    },
    async uploadFile(filePath) {
      try {
        const result = await upload({ url: '/file/upload', filePath, name: 'file' })
        const url = result?.data?.url || filePath
        return url
      } catch(e) { uni.showToast({ title:'上传失败', icon:'none' }); return '' }
    },
    async submit() {
      // 校验
      if (!this.form.title) return uni.showToast({ title:'请输入标题', icon:'none' })
      if (!this.form.departmentId) return uni.showToast({ title:'请选择就诊科室', icon:'none' })
      if (!this.form.diseaseName) return uni.showToast({ title:'请选择或输入主要病症', icon:'none' })
      if (!this.form.diseaseDetail) return uni.showToast({ title:'请输入病症详情', icon:'none' })
      if ((this.form.diseaseDetail||'').length > 300) return uni.showToast({ title:'病症详情不超过300字', icon:'none' })
      if (this.form.rewardEnabled === 1) {
        const val = Number(this.form.rewardCoin)
        if (!val || val <= 0) return uni.showToast({ title:'请输入有效的赏币数量', icon:'none' })
        if (this.coinBalance !== null && val > this.coinBalance) return uni.showToast({ title:'H币余额不足，请先充值', icon:'none' })
      }

      // 提交前：将本地临时图片上传，得到真实 URL
      let finalImages = []
      try {
        uni.showLoading({ title:'图片上传中', mask:true })
        for (const u of (this.images || [])) {
          if (this.isNetUrl(u)) {
            finalImages.push(u)
          } else {
            const url = await this.uploadFile(u)
            if (url) finalImages.push(url)
          }
        }
      } finally {
        uni.hideLoading()
      }

      const payload = { ...this.form }
      payload.image = finalImages.join(',')

      this.submitting = true
      try {
        const res = await publishCircle(payload)
        if (res && (res.code === 200 || res.success)) {
          uni.showToast({ title: '发布成功', icon: 'success' })
          setTimeout(()=> uni.navigateBack(), 1000)
        } else {
          uni.showToast({ title: (res && res.msg) || '发布失败', icon: 'none' })
        }
      } catch(e) {
        uni.showToast({ title: '发布异常', icon: 'none' })
      } finally {
        this.submitting = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.publish-page{ min-height:100vh; background:#f7f8fa; }
.nav{ position:fixed; top:0; left:0; right:0; height:88rpx; background:#fff; display:flex; align-items:center; justify-content:space-between; padding:0 28rpx; z-index:9; border-bottom:1px solid #eee; }
.back{ width:56rpx; height:56rpx; border-radius:28rpx; background:#f2f3f5; display:flex; align-items:center; justify-content:center; font-size:34rpx; }
.title{ font-weight:600; font-size:32rpx; }
.body{ padding: 16rpx; height: calc(100vh - 88rpx); box-sizing: border-box; }
.card{ background:#fff; border-radius:16rpx; padding:20rpx; margin-bottom:16rpx; position:relative; }
.field{ margin-bottom:16rpx; position:relative; }
.field.two{ display:flex; gap:12rpx; }
.field.two .half{ flex:1; }
.label{ display:block; color:#333; font-size:28rpx; margin-bottom:10rpx; }
.input{ height:88rpx; background:#f6f7fb; border-radius:14rpx; padding:0 20rpx; font-size:28rpx; }
.textarea{ min-height:160rpx; width:100%; background:#f6f7fb; border-radius:14rpx; padding:16rpx; font-size:28rpx; box-sizing:border-box; }
.count{ position:absolute; right:8rpx; bottom:8rpx; color:#999; font-size:22rpx; }
.picker{ height:88rpx; background:#f6f7fb; border-radius:14rpx; display:flex; align-items:center; padding:0 20rpx; color:#666; }
.chips-wrap{ display:flex; flex-wrap:wrap; gap:16rpx 20rpx; padding:12rpx 4rpx 8rpx; }
.chip{ padding:12rpx 22rpx; background:#f6f7fb; border-radius:999rpx; color:#333; font-size:26rpx; border:1px solid #eaeaea; }
.chip.active{ background:#eef2ff; color:#4f46e5; border-color:#c7d2fe; }
.reward-tip{ color:#666; font-size:24rpx; margin-bottom:16rpx; }
.amounts{ display:flex; gap:16rpx; flex-wrap:wrap; margin-bottom:12rpx; }
.amount-chip{ padding:18rpx 28rpx; border-radius:12rpx; background:#f6f7fb; border:1px solid #e5e7eb; color:#333; font-size:28rpx; }
.amount-chip.active{ background:#eef2ff; color:#4f46e5; border-color:#c7d2fe; }
.balance{ color:#888; font-size:24rpx; }
.recharge{ color:#4f46e5; margin-left:8rpx; }
.images{ display:flex; flex-wrap:wrap; gap:12rpx; }
.img-item{ width:200rpx; height:200rpx; border-radius:12rpx; overflow:hidden; background:#f2f3f5; position:relative; }
.img{ width:100%; height:100%; }
.img-item.upload{ display:flex; align-items:center; justify-content:center; border:1px dashed #ccc; }
.plus{ font-size:60rpx; color:#bbb; }
.del{ position:absolute; right:6rpx; top:6rpx; width:36rpx; height:36rpx; background:rgba(0,0,0,.6); color:#fff; border-radius:18rpx; display:flex; align-items:center; justify-content:center; }
.footer{ position:fixed; left:0; right:0; bottom:0; background:#fff; padding:16rpx 16rpx calc(16rpx + env(safe-area-inset-bottom)); box-shadow:0 -6rpx 20rpx rgba(0,0,0,.06); }
.submit{ background:linear-gradient(135deg, #667eea 0%, #764ba2 100%); color:#fff; border-radius:14rpx; height:90rpx; line-height:90rpx; font-size:32rpx; }
.safe{ height: 120rpx; }
</style>
